package actions;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import java.util.*;

import javax.ejb.Local;
import javax.mail.internet.AddressException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.struts2.components.ActionError;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import utils.*;
import beans.*;
import entities.*;

public class RegisterAction extends ActionSupport {

	// Comment for JBoss
	@EJB
	private UserManagerLocal userManager = new UserManager();

	// Uncomment for JBoss [I know it's not a word]
	// private UserManagerLocal userManager;

	private User user;
	private static final long serialVersionUID = 3L;

	public RegisterAction() {
		// Uncomment for JBoss
		/*
		 * Stateless name =
		 * (Stateless)UserManager.class.getAnnotation(Stateless.class); String
		 * mName = name.mappedName(); userManager =
		 * EJBFactory.createSessionBean(UserManagerLocal.class, mName);
		 */
		user = new User();
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String execute() {

		// by default set the type to user
		if (user.getUserType() == null || user.getUserType().equals(""))
			user.setUserType("user");

		try {
			javax.mail.internet.InternetAddress iaddr = new javax.mail.internet.InternetAddress(user.getUserName(), true);
		} catch (AddressException e) {

			this.addActionError("Invalid email address");
			return ERROR;
		}
		
		// add the user
		int id = userManager.addUser(user);
		if(id>0){
			this.addActionMessage(" Your account was updated successfully. ");
		}else{
			this.addActionError("An error has occurred while updating your account. Please try again");
		}
		// put this info into HTTP Session variable
		ActionContext.getContext().getSession().put("userId", new Integer(id));

		return SUCCESS;

	}
}